<template>
  <div class="h-full flex flex-col">
    <div class="z--1">
      <img src="https://jwc-static.jdwxk.com/imgs/user/write-off-bg.png" class="absolute h-full w-full" alt="">
    </div>
    <div class="h-full w-full overflow-y-scroll p-x-5 pt-15">
      <div class="relative w-full flex justify-center p-y-5 text-4.5 text-white">
        <p>核销二维码</p>
        <img src="https://jwc-static.jdwxk.com/imgs/user/box.png" class="absolute inset-0 z--1 h-full rounded-2" alt="">
      </div>
      <div class="flex flex-col items-center border-3 border-#C94B3A rounded-2 border-solid bg-#FFF8F2 p-y-5">
        <p class="text-4 text-#333">
          奖品：{{ orderData.goodsName }}
        </p>
        <p class="m-t-1 text-3 text-#999">
          请将本二维码出示给核销员
        </p>
        <div class="relative m-y-10 h-60 w-60">
          <QrCode v-if="code" ref="qrcodeRef" :text="code" />
          <div v-if="orderData.status === 1" class="absolute inset-0 flex items-center justify-center bg-white/30 backdrop-blur-15">
            <p class="text-4 text-#CE4A3C">
              已核销
            </p>
          </div>
        </div>
      </div>
      <div class="m-y-5 flex justify-center gap-5" @click="getData">
        <Btn v-if="orderData.status === 0" class="w-35" @click="handleSuccess">
          确认
        </Btn>
        <Btn v-else class="w-40" @click="handleBack">
          返回
        </Btn>
        <Btn v-if="orderData.status === 0" class="w-35" @click="handleSaveQrCode">
          保存图片
        </Btn>
      </div>
    </div>
    <SuccessDialog :show="showSuccess" @update:show="handleClickSuccess" />
    <FailDialog
      v-model:show="showFail" :data="{
        title: '未核销',
        content: '请前往核销人员处核销',
      }"
    />
  </div>
</template>

<script setup lang="ts">
import SuccessDialog from './Success/index.vue'
import QrCode from '@/components/QrCode.vue'
import Btn from '@/components/Btn.vue'
import { getOrderDataByCode } from '@/api/home'
import type { IOrderData } from '@/api/home/types'
import FailDialog from '@/views/mall/goods-detail/OrderConfirmation/FailDialog/index.vue'

const showSuccess = ref(false)
const showFail = ref(false)
const route = useRoute()
const router = useRouter()

const code = computed(() => {
  return route.query.code as string
})
const orderData = ref<IOrderData>({} as IOrderData)
async function getData() {
  if (!code.value) {
    return
  }
  const res = await getOrderDataByCode(code.value)
  orderData.value = res.data
}

getData()

function handleBack() {
  router.replace('/redemption-center')
}

async function handleSuccess() {
  await getData()
  if (orderData.value.status === 1) {
    showSuccess.value = true
  }
  else {
    showFail.value = true
  }
}

function handleClickSuccess() {
  handleBack()
}

const qrcodeRef = ref<InstanceType<typeof QrCode> | null>(null)

function handleSaveQrCode() {
  qrcodeRef.value?.save()
}
</script>

<style scoped lang="less"></style>
